package com.gxljc.bear.crawler.weixin;

import com.gxljc.commons.util.AdvFile;
import com.gxljc.commons.util.ILineParser;
import com.gxljc.commons.util.StringUtil;
import com.gxljc.bear.crawler.base.DolphinCrawlerConf;
import com.gxljc.bear.crawler.util.DateUtil;
import com.gxljc.bear.crawler.util.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/10/11.
 */
public class WeixinUtil {
    public static Logger LOG = Logger.getLogger(WeixinUtil.class);

    //生成微信唯一ID
//    public static String genWid(String url) {
//        if (StringUtils.isEmpty(url)) return null;
//        //http://mp.weixin.qq.com/s?__biz=MjM5NDUzMDQxNA==&mid=2662380730&idx=3&sn=5e83d7413447352d5dd63323561d4f6f#rd
//        final String bizParse = "(_biz=.*?&)";
//        final String midParse = "(mid=\\d+&)";
//        final String idxParse = "(idx=\\d+&)";
//        final String snParse = "(sn=.*?)[#&]";
//        String biz = parseWid(bizParse, url);
//        String mid = parseWid(midParse, url);
//        String idx = parseWid(idxParse, url);
//        String sn = parseWid(snParse, url);
//        String wid = biz + mid + idx + sn;
//        System.out.println("wid=" + wid);
//        return MD5Util.getMd5(wid);
//    }

    //生成微信唯一ID
    public static String genWid(PageTable table) throws Exception {
        if (StringUtils.isEmpty(table.title) || StringUtils.isEmpty(table.accountId) || table.publishDate == null)
            throw new Exception("title, accountId, publishDate is error");
        String publishDateStr = DateUtil.dateFormat(table.publishDate, "yyyy-MM-dd");
        String wid = table.title + "-" + table.accountId + "-" + publishDateStr;
//        System.out.println("wid=" + wid);
        return MD5Util.getMd5(wid);
    }

    //生成微信唯一ID
    private static String parseWid(String reg, String url) {
        Pattern pattern = Pattern.compile(reg);
        Matcher m = pattern.matcher(url);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }

    public static void failTime(PageTable table, String tableName) {
        Integer failTime = table.getFailTime();
        if (failTime == null) failTime = 1;
        else failTime = failTime.intValue() + 1;
        if (failTime.intValue() < WeixinConst.MAX_WEIXIN_PAGE_FAIL_TIME) {
            PageTable newTable = new PageTable();
            newTable.pageId = table.pageId;
            newTable.failTime = failTime;
            try {
                WeixinMongodbUtil.savePageMongodb(newTable, tableName);
            } catch (Exception e) {
                e.printStackTrace();
                LOG.error("save page fail time error = " + table.pageId);
            }
        } else {
            try {
                WeixinMongodbUtil.deletePageMongodb(table.pageId, tableName);
            } catch (Exception e) {
                e.printStackTrace();
                LOG.error("delete pageid error = " + table.pageId);
            }
        }
    }

    public static List<AccountTable> getAccountSeed() throws Exception {
        final String filename = "weixin_all.txt";
        Configuration conf = DolphinCrawlerConf.getInstance();
        final List<AccountTable> seeds = new LinkedList<AccountTable>();
        AdvFile.loadFileInDelimitLine(
                conf.getConfResourceAsInputStream(filename), new ILineParser() {
                    @Override
                    public void parseLine(String line) {
                        String[] split = line.split(StringUtil.STR_DELIMIT_3RD);
                        if (split.length != 4) {
                            return;
                        }
                        String word1 = split[0].trim();
                        String word2 = split[1].trim();
                        String word3 = split[2].trim();
                        String word4 = split[3].trim();
                        if (word1.isEmpty() || word2.isEmpty() || word3.isEmpty() || word4.isEmpty()) {
                            return;
                        }
                        AccountTable table = new AccountTable();
                        table.setName(word1);
                        table.setAccountId(word2);
                        table.setAccountType(word3);
                        table.setTargetType(word4);
                        seeds.add(table);
                    }
                });
        return seeds;
    }
}
